package com.dd.shop4j.common.utils;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.imageio.ImageIO;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * 图片处理公用类
 * 
 * @author Administrator
 * 
 */
public class ImageUtils {

	private static final Logger logger = Logger.getLogger(ImageUtils.class);
	private static final DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
	private static final String dir = System.getProperty("user.dir") + "\\src\\main\\webapp\\resources\\data\\";
	private static final String webDir = "resources/data/";
	
	/**
	 * 简单文件上传
	 * @param file
	 * @return
	 */
	public static String simpleUpload(MultipartFile file) {
		if (file == null || file.getSize() <= 0) {
			logger.info("未选中文件或者文件为空。");
			return null;
		}
		if (StringUtils.isNotEmpty(file.getContentType())
				&& file.getContentType().indexOf("image") > -1) {
			String seria = df.format(new Date());
			String orgFileName = file.getOriginalFilename();
			try {
				zipImage(file, dir + seria + "_" + orgFileName, 0);
			} catch (IOException e) {
				e.printStackTrace();
			}
			logger.info("图片上传至：" + webDir + seria + "_" + orgFileName);
			return webDir + seria + "_" + orgFileName;
		}
		return null;
	}
	
	/**
	 * 文件上传,图片将会被分为：原图，大图，中图，小图
	 * @param file
	 * @return
	 */
	public static ImageInfo upload(MultipartFile file) {
		try {
			if (file == null || file.getSize() <= 0) {
				logger.info("未选中文件或者文件为空。");
				return null;
			}
			if (StringUtils.isNotEmpty(file.getContentType())
					&& file.getContentType().indexOf("image") > -1) {
				String seria = df.format(new Date());
				String orgFileName = file.getOriginalFilename();
				ImageInfo image = new ImageInfo();
				//上传原图
				zipImage(file, dir + seria + "_src_" + orgFileName, 0);
				image.setSrcPath(webDir + seria + "_src_" + orgFileName);
				logger.info("原图上传至：" + webDir + seria + "_src_" + orgFileName);
				//上传大图
				zipImage(file, dir + seria + "_big_" + orgFileName, 600);
				image.setBigPath(webDir + seria + "_big_" + orgFileName);
				logger.info("大图上传至：" + webDir + seria + "_big_" + orgFileName);
				//上传中图
				zipImage(file, dir + seria + "_midd_" + orgFileName, 300);
				image.setMiddPath(webDir + seria + "_midd_" + orgFileName);
				logger.info("中图上传至：" + webDir + seria + "_midd_" + orgFileName);
				//上传小图
				zipImage(file, dir + seria + "_small_" + orgFileName, 150);
				image.setSmallPath(webDir + seria + "_small_" + orgFileName);
				logger.info("小图上传至：" + webDir + seria + "_small_" + orgFileName);
				return image;
			} else {
				logger.info("上传非图片，文件类型为:" + file.getContentType());
			}
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("文件上传失败:" + e.getMessage());
		}
		return null;
	}

	/**
	 * 压缩图片
	 * @param file 上传图片
	 * @param zipPath 压缩路径
	 * @param width	压缩宽度    压缩高度会根据宽度与原图的比例自动计算
	 * @throws IOException
	 */
	public static void zipImage(MultipartFile file, 
			String zipPath, int width) throws IOException {
		//如果高宽都大于0，那么需要压缩图片
		if (width > 0) {
			BufferedImage img = ImageIO.read(file.getInputStream());
			int height = img.getHeight() * width / img.getWidth();
			BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);    
            tag.getGraphics().drawImage(img.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);   
			FileOutputStream out = new FileOutputStream(zipPath);   
			// JPEGImageEncoder可适用于其他图片类型的转换    
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);    
			encoder.encode(tag);    
			out.close();
			return;
		}
		FileUtils.copyInputStreamToFile(file.getInputStream(), new File(zipPath));
	}
	
	/**
	 * 删除不要的图片
	 * @param path
	 */
	public static void deleteImage(String path) {
		File imageFile = new File(dir + path.replace(webDir, ""));
		if (imageFile.isFile()) {
			imageFile.delete();
			logger.info("删除图片:" + path);
		}
	}
	
	/**
	 * 图片内部类，用于封装路径
	 * @author Administrator
	 *
	 */
 	public static class ImageInfo implements Serializable {
		
		private static final long serialVersionUID = -3487550817604447742L;
		
		private String srcPath;
		private String bigPath;
		private String middPath;
		private String smallPath;

		public String getSrcPath() {
			return srcPath;
		}

		public void setSrcPath(String srcPath) {
			this.srcPath = srcPath;
		}

		public String getBigPath() {
			return bigPath;
		}

		public void setBigPath(String bigPath) {
			this.bigPath = bigPath;
		}

		public String getMiddPath() {
			return middPath;
		}

		public void setMiddPath(String middPath) {
			this.middPath = middPath;
		}

		public String getSmallPath() {
			return smallPath;
		}

		public void setSmallPath(String smallPath) {
			this.smallPath = smallPath;
		}
	}

}
